package gwu.android;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Simple article words database access helper class. Defines the basic CRUD operations
 * for the ReaderApp, and gives the ability to list all articles as well as
 * retrieve or modify a specific article.
 */
public class WordItemsDbAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_ARTICLEID = "_artID";
    public static final String KEY_WORDID = "_wIndex";
    public static final String KEY_ANSWER = "answer";
    public static final String KEY_FOIL1 = "foil1";
    public static final String KEY_FOIL2 = "foil2";
    public static final String KEY_FOIL3 = "foil3";
    public static final String KEY_SCORE = "score"; //0: Not answered 1: Right -1: Wrong

    private static final String TAG = "WordItemsDbAdapter";
    private DatabaseHelper mDbHelper2;
    private SQLiteDatabase mDb2;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table worditems (_id integer primary key autoincrement, "
        + "_artID articleID text not null, _wIndex answer text not null, answer text not null, "
        + "foil1 text not null, foil2 text not null, foil3 text not null, score integer);";

    private static final String DATABASE_NAME = "words";
    private static final String DATABASE_TABLE = "worditems";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS worditems");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public WordItemsDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the article database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public WordItemsDbAdapter open() throws SQLException {
        mDbHelper2 = new DatabaseHelper(mCtx);
        mDb2 = mDbHelper2.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper2.close();
    }


    /**
     * Create a new word item row using provided info. If the article is
     * successfully created return the new rowId for that article, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the article
     * @param body the body of the article
     * @return rowId or -1 if failed
     */
    public long createWordItem(Long artId, int wordId, String answer, 
    		String foil1, String foil2, String foil3, int score) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ARTICLEID, artId);
        initialValues.put(KEY_WORDID, wordId);
        initialValues.put(KEY_ANSWER, answer);
        initialValues.put(KEY_FOIL1, foil1);
        initialValues.put(KEY_FOIL2, foil2);
        initialValues.put(KEY_FOIL3, foil3);
        initialValues.put(KEY_SCORE, score);

        return mDb2.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the word item rows with the given article Id
     * 
     * @param artId id of article word items to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteArticleWords(long artId) {

        return mDb2.delete(DATABASE_TABLE, KEY_ARTICLEID + "=" + artId, null) > 0;
    }
    
    /**
     * Return the score of an article.
     */
    public ArrayList<Integer> scoreArticle(Cursor wordItems){
    	int score = 0;
    	ArrayList<Integer> scores = new ArrayList<Integer>();
    	for(int i = 0; i < wordItems.getCount(); i++){
    		scores.add(wordItems.getInt(wordItems.getColumnIndexOrThrow(KEY_SCORE)));
//        	score += wordItems.getInt(wordItems.getColumnIndexOrThrow(KEY_SCORE));
        	wordItems.moveToNext();
    	}
    	return scores;
    }


    /**
     * Return a Cursor positioned at the first word item in the table with from the article 
     * that matches the given rowId (rowId of the article in the ArticleDb is the article id)
     * 
     * @param rowId id of article word items to retrieve
     * @return Cursor positioned to matching article word items, if found
     * @throws SQLException if article could not be found/retrieved
     */
    public Cursor fetchArticle(long rowId) throws SQLException {

        Cursor mCursor =

            mDb2.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_ARTICLEID, KEY_WORDID, KEY_ANSWER, KEY_FOIL1, 
                    KEY_FOIL2, KEY_FOIL3, KEY_SCORE}, KEY_ARTICLEID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the word item using the details provided. The word item to be updated is
     * specified using the rowId, and it is altered to use the new score
     * 
     * @param rowId id of article to update
     * @param wordId id of the word to update
     * @param score
     * @return true if the article was successfully updated, false otherwise
     */
    public boolean updateScore(long rowId, String wordId, int score) {
        ContentValues args = new ContentValues();
        args.put(KEY_WORDID, wordId);
        args.put(KEY_ARTICLEID, rowId);
        args.put(KEY_SCORE, score);

        return mDb2.update(DATABASE_TABLE, args, KEY_ARTICLEID + "=" + rowId + "" + " and " + KEY_WORDID + "=" + wordId, null) > 0;
    }

}
